package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {


    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Stock newStock = new Stock();
            @NotNull @Min(0) Long itemId = cartProductDto.getProductId();
            newStock.setItemId(itemId);
            try {
                Stock stock = stockMapper.selectByPrimaryKey(itemId);
                newStock.setStockCount(stock.getStockCount() - cartProductDto.getProductNum());
                newStock.setLockCount((int) (stock.getLockCount() + cartProductDto.getProductNum()));
                stockMapper.updateByPrimaryKeySelective(newStock);
            } catch (Exception e) {
                throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),
                        OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
            }
        }

        return true;
    }
}
